import { PlusOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import { Button, message, Popconfirm, Drawer } from 'antd';
import React, { useState, useRef } from 'react';
import { useIntl, FormattedMessage } from 'umi';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { BetaSchemaForm } from '@ant-design/pro-components';

const ACTION_TEXTS = {
  EDIT: '编辑',
  DELETE: '删除',
  NEW: '新建'
}
const ButtonRender = ({type, onNew}: any) => {
  if (type === 'NEW') {
    return (
      <Button
              type="primary"
              key="primary"
              onClick={onNew}
            >
              <PlusOutlined /> <FormattedMessage id="pages.searchTable.new" defaultMessage="新建" />
            </Button>
    )
  }
  return null
}
const ListView: React.FC = ({ACTIONS, columns, formColumns, request, rowKey, ...props}: any) => {
  /** 新建窗口的弹窗 */
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  /** 分布更新窗口的弹窗 */
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);

  const [showDetail, setShowDetail] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.AuthorityListItem>();
  const [currentParentId, setCurrentParentId] = useState<string|undefined>('');
  const [selectedRowsState, setSelectedRows] = useState<API.AuthorityListItem[]>([]);
  const [editRecord, setEditRecord] = useState(null)


  const toolbarButtons = ACTIONS.map((action: any) => (
    <ButtonRender {...action} onNew={() => {
      handleModalVisible(true);
    }}/>
  ))

  const newAction = ACTIONS.find((a: any) => a.type === 'NEW')
  const editAction = ACTIONS.find((a: any) => a.type === 'EDIT')
  const deleteAction = ACTIONS.find((a: any) => a.type === 'DELETE')

  if (editAction || deleteAction || (newAction && newAction.inline)) {

    const optButton = {
      title: '操作',
      valueType: 'option',
      key: 'option',
      render: (text, record, _, action) => [
        editAction && <a
        key="editable"
        onClick={() => {
          setEditRecord(record);
          handleModalVisible(true);
        }}
      >
        {editAction.text || ACTION_TEXTS[editAction.type]}
      </a>,
        deleteAction &&
        <Popconfirm title="确定要删除嘛？" icon={<QuestionCircleOutlined style={{ color: 'red' }} />} onConfirm={async () => {
          try {
            await deleteAction.submit(record)
            action.reload()
          } catch(e) {}
        }}>
          <a href="#">{deleteAction.text || ACTION_TEXTS[deleteAction.type]}</a>
        </Popconfirm>,

        newAction && newAction.inline &&
          <a
            key="editable"
            onClick={() => {
              setEditRecord({parentId: record.id});
              handleModalVisible(true);
            }}
          >
            {newAction.text || ACTION_TEXTS[newAction.type]}
          </a>,
        ],
    }


    columns = [...columns, optButton]
  }

  return (
    <PageContainer>
      <ProTable
        {...props}

        actionRef={actionRef}
        rowKey={"id"}
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => toolbarButtons}
        request={request}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              <FormattedMessage id="pages.searchTable.chosen" defaultMessage="已选择" />{' '}
              <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a>{' '}
              <FormattedMessage id="pages.searchTable.item" defaultMessage="项" />
              &nbsp;&nbsp;
              <span>
                <FormattedMessage
                  id="pages.searchTable.totalServiceCalls"
                  defaultMessage="服务调用次数总计"
                />{' '}
                {selectedRowsState.reduce((pre, item) => pre + item.callNo!, 0)}{' '}
                <FormattedMessage id="pages.searchTable.tenThousand" defaultMessage="万" />
              </span>
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            <FormattedMessage id="pages.searchTable.batchDeletion" defaultMessage="批量删除" />
          </Button>
          <Button type="primary">
            <FormattedMessage id="pages.searchTable.batchApproval" defaultMessage="批量审批" />
          </Button>
        </FooterToolbar>
      )}
      {newAction && <BetaSchemaForm
        layoutType="ModalForm"
        layout="horizontal"
        grid={true}
        rowProps={{
          gutter: [16, 16],
        }}
        colProps={{
          span: 14,
        }}
        open={createModalVisible}
        onOpenChange={(visible) => {
          handleModalVisible(visible);
          if (!visible) {
            setEditRecord({})
          }
        }}

        title="弹窗"
        columns={formColumns}
        initialValues={editRecord}
        modalProps={{destroyOnClose:true}}
        onFinish={async (values: any) => {
          console.log('data---->', values)
          const hide = message.loading('正在添加');
          try {
            let body = {...values}
            if (newAction.beforeSubmit) {
              body = newAction.beforeSubmit(body)
            }
            newAction.submit(editRecord && editRecord.id, body)

            hide();
            message.success('添加成功');
            actionRef.current?.reload()
            handleModalVisible(false);
            return true;
          } catch (error) {
            console.log('error', error)
            hide();
            message.error('添加失败请重试！');
            return false;
          }
        }}
      />}
    </PageContainer>
  );
};

export default ListView;
